<?php

/**
 * Модель дополнений
 */
class AddonsModel extends DbModel {

    protected $_name = 'addons';

    /**
     * Установка дополнения
     *
     * @param string $file Установочный файл
     * @return int #ID записи
     */
    public function installAddon($file) {
        $zip = new ZipArchive();
        if ($zip->open($file) !== TRUE) {
            return false;
        } else {
            $public = array();
            $app = array();
            
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $name = $zip->getNameIndex($i);
                if (strpos($name, 'public/') === 0) {
                    $newname = str_replace('public/', '', $name);
                    if ($newname <> '') {
                        $zip->renameName($name, $newname);
                        $public[] = $newname;
                    }
                } else {
                    if (strtolower($name) <> 'install.php') {
                        $app[] = $name;
                    } else {
                        $code = $zip->getFromName('install.php');
                    }
                }
            }            
            if ($code <> '')
                eval(str_replace('<?php', '', $code));
            
            $addon = $this->getAddonByTitle($package['title']);
                    
            if (is_null($addon)) {
                $this->insert($package);
                $id = $this->_db->lastInsertId();
            } else {
                $id = $addon->id;
                $this->update($package, 'id = ' . $id);
            }

            $zip->extractTo(PUBLIC_PATH , $public);
            $zip->extractTo(PUBLIC_PATH . '/..', $app);
            return $id;
        }
    }

    /**
     * Удаление дополнения
     *
     * @param int $id #ID расширения
     */
    public function deleteAddon($id) {
        $this->delete("id = " . $id);
        return true;
    }

    /**
     * Получение списка дополнений
     *
     * @param string $type Тип дополнения
     * @param id $id #ID дополнения
     * @return mixed Список дополнений
     */
    public function getAddons($type = '', $id = 0) {
        $db = $this->_db;
        if ($type <> '') {
            $select = $db->select()->from(PREFIX . 'addons')->where('type = ?', $type)->order('name');
        } else {
            $select = $db->select()->from(PREFIX . 'addons')->order('name');
        }
        if ($id > 0) {
            $select->where('id = ?', $id);
            $res = $db->fetchRow($select);
        } else {
            $res = $db->fetchAll($select);
        }
        return $res;
    }

    /**
     * Получение дополнения по имени
     *
     * @param str $title
     * @return array
     */
    public function getAddonByTitle($title) {
        $select = $this->select()->where('title = ?' , $title);
        $res = $this->fetchRow($select);
        return $res;
    }

    /**
     * Получение списка дополнений в виде массива
     *
     * @param string $type Тип дополнения
     * @param string $col 2 возвращаемый столбец после id
     * @return mixed Список дополнений
     */
    public function getAddonsList($type = '', $col = 'name') {
        $db = $this->_db;
        if ($type <> '') {
            $select = $db->select()->from(PREFIX . 'addons', array('id', $col))->where('type = ?', $type)->order($col . ' ASC');
            if ($type == 'template') {
                $select->where("title <> 'default'");
            }
        } else {
            $select = $db->select()->from(PREFIX . 'addons', array('id', $col))->order($col . ' ASC');
        }
        $res = $db->fetchPairs($select);
        return $res;
    }
    
    /**
     * Полученеи перевода
     * 
     */
    public function getTranslate($lang = '') {
        if ($lang == ''){
            $config = Zend_Registry::get('config');
            $lang = $config->lang;
        }
        
        $adapter = new Zend_Translate('gettext', APP_PATH . '/languages/' . $lang . '.mo', $lang);
        Zend_Registry::set('Zend_Locale', $adapter);
        Zend_Registry::set('Zend_Translate', $adapter);
        /*$zend_form_array = array(
            _("notAlnum"),
            _("stringEmpty"),
            _("notAlpha"),
            _("notBetween"),
            _("notBetweenStrict"),
            _("ccnumLength"),
            _("ccnumChecksum"),
            _("dateNotYYYY-MM-DD"),
            _("dateInvalid"),
            _("dateFalseFormat"),
            _("notDigits"),
            _("emailAddressInvalid"),
            _("emailAddressInvalidFormat"),
            _("emailAddressInvalidHostname"),
            _("emailAddressInvalidMxRecord"),
            _("emailAddressDotAtom"),
            _("emailAddressQuotedString"),
            _("emailAddressInvalidLocalPart"),
            _("notFloat"),
            _("notGreaterThan"),
            _("notHex"),
            _("noRecordFound"),
            _("hostnameIpAddressNotAllowed"),
            _("hostnameUnknownTld"),
            _("hostnameDashCharacter"),
            _("hostnameInvalidHostnameSchema"),
            _("hostnameUndecipherableTld"),
            _("hostnameInvalidHostname"),
            _("hostnameInvalidLocalName"),
            _("hostnameLocalNameNotAllowed"),
            _("notSame"),
            _("missingToken"),
            _("notInArray"),
            _("notInt"),
            _("notIpAddress"),
            _("notLessThan"),
            _("isEmpty"),
            _("recordFound"),
            _("regexNotMatched"),
            _("stringLengthTooShort"),
            _("stringLengthTooLong"),
            _("badCaptcha"),
            _("missingValue"),
            _("errCaptcha")
        );*/
        return $adapter;
    }    
    
    public function addTranslate($addon,$lang = '') {
        if ($lang == ''){
            $config = Zend_Registry::get('config');
            $lang = $config->lang;
        }
        $t = Zend_Registry::get('Zend_Locale');
        if (file_exists(APP_PATH . '/languages/' . $lang . '_' . $addon . '.mo')){
            $t->addTranslation(
                array(
                    'content' => APP_PATH . '/languages/' . $lang . '_' . $addon . '.mo',
                    'locale'  => $lang
                )
            );
        }       
    }
}